Page({
  data: {
    userID: '',
  },
  onLoad() {
    let userID = wx.getStorageSync('userID')
    if (!!userID) {
      this.setData({
        userID
      })
    } else {
      this.handleLogin()
    }
  },
  handleLogin() {
    const that = this;
    wx.login({
      success: res => {
        if (res.code) {
          wx.request({
            url: 'https://api.weixin.qq.com/sns/jscode2session',
            method: 'post',
            data: {
              js_code: res.code,
              appid: 'wx6cf30b652f10a1da',
              secret: 'c58bbac5845bbcba6f31ea1003bf3a95',
              grant_type: 'authorization_code'
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded',
            },
            success: result => {
              console.log('openid===', result.data)
              wx.setStorageSync('userID', result.data.openid)
              that.setData({
                userID: result.data.openid,
              })
            }
          })
        }
      }
    })
  },
  getUserInfo() {
    const that = this;
    wx.getUserProfile({
      desc: '用于完善用户资料',
      success: res => {
        wx.setStorageSync('userID', res.signature)
        that.setData({
          userID: res.signature,
        })
      },
      fail: err => {
        wx.showToast({
          title: '用户已拒绝',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  handleRecord() {
    wx.navigateTo({
      url: '/pages/record/index',
    })
  },
  handleCreate() {
    wx.navigateTo({
      url: '/pages/create/index',
    })
  }
})